//
//  ViewController.m
//  RuntimeDemo
//
//  Created by zxs on 2021/2/22.
//

#import "ViewController.h"
#import "Person.h"
#import <objc/runtime.h>
#import "Person+AddProperty.h"

@interface ViewController ()

@property (nonatomic, strong) Person *person;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化
    self.person = [[Person alloc] init];
}

// 修改属性值
- (IBAction)modifyButtonTouched:(id)sender {
    // 公共属性，可以在外部设置
    self.person.age = 30;
    self.person.name = @"小明";
    // nickName是私有属性，无法设置
    
    NSLog(@"修改前：");
    NSLog(@"%@", self.person);
    unsigned int count = 0;
    Ivar *ivar = class_copyIvarList(self.person.class, &count);
    for (int i = 0; i < count; i++) {
        Ivar tempIvar = ivar[i];
        const char *varName = ivar_getName(tempIvar);
        NSString *varNameString = [NSString stringWithUTF8String:varName];
             
        // 名字；公共属性，可以修改
        if ([varNameString isEqualToString:@"_name"]) {
            object_setIvar(self.person, tempIvar, @"小明的新名字");
        }
        
        // 年龄；值类型；感觉上修改成功了；但是NSNumber的打印（就是Description）不正常；
        if ([varNameString isEqualToString:@"_age"]) {
            object_setIvar(self.person, tempIvar, @11);
        }
        
        // 昵称是私有属性，也能修改
        if ([varNameString isEqualToString:@"_nickname"]) {
            object_setIvar(self.person, tempIvar, @"小明的昵称");
        }
    }
    
    // 释放
    free(ivar);
    
    NSLog(@"修改后：");
    NSLog(@"%@", self.person);
}

// 分类添加属性
- (IBAction)categoryButtonTouched:(id)sender {
    // 设置原有的公共属性
    self.person.name = @"小明同学";
    self.person.age = 41;
    
    // 设置通过分类添加的属性
    self.person.height = 188;
    self.person.career = @"iOS架构师";
    self.person.location = CGPointMake(1280, 30);
    NSLog(@"%@", self.person);
}



@end
